<?php

if (!class_exists("PST_DATETIME")) {

    class PST_DATETIME extends PST_PRESENTATION {

        public function __construct($settings) {
            parent::__construct($settings);

            if (empty($this->array['type'])) {
                $this->array['type'] = "text";
                $this->array['class'] = "datetimepicker";
            }

            if (isset($this->classparams["force"]) && $this->classparams["force"] && empty($this->value)) {
                $this->value = date("d/m/Y H:i:s");
            }
        }

        public function objectDBQuery() {
            if (isset($this->field) && isset($this->value)) {
                if (strpos($this->value, "/") !== false) {
                    $array1 = explode(" ", $this->value);
                    $array2 = explode("/", $array1[0]);
                    $value = $array2[2] . "-" . $array2[1] . "-" . $array2[0] . " " . $array1[1];
                    return array($this->field . " LIKE" => "%" . $value . "%");
                } else {
                    return array($this->field . " LIKE" => "%" . $this->value . "%");
                }
            }
            return array();
        }

        public function loadDbQuery() {
            if (isset($this->value)) {
                if (strpos($this->value, "-") !== false) {
                    $array1 = explode(" ", $this->value);
                    $array2 = explode("-", $array1[0]);
                    $value = $array2[2] . "/" . $array2[1] . "/" . $array2[0] . " " . $array1[1];
                    return $value;
                } else {
                    return $this->value;
                }
            }
            return "";
        }

        public function saveDbQuery() {
            if (isset($this->value)) {
                if (strpos($this->value, "/") !== false) {
                    $array1 = explode(" ", $this->value);
                    $array2 = explode("/", $array1[0]);
                    
                    $dia = $array2[2] . "-" . $array2[1] . "-" . $array2[0];
                    $hora = strlen($array1[1]) == 5 ? $array1[1] . ":00" : $array1[1];
                    
                    return $dia . " " . $hora;
                } else {
                    return $this->value;
                }
            }
            return "";
        }

    }

}
